package com.nio.netty.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.UUID;

import static io.netty.util.CharsetUtil.UTF_8;

public class MyServerHandler  extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        /*接收到数据并处理*/
        int len = msg.getLen();
        byte[] content = msg.getContent();

        /*将字节数组转成字符串*/
        String message = new String(content, UTF_8);
        System.out.println("服务器接受到数据长度:"+len);
        System.out.println("服务器接受到消息内容:"+message);

        System.out.println("服务器接收到消息包数量："+(++this.count));

        /*服务器回送数据给客户端，回送一个随机的ID*/
        String responseContent=UUID.randomUUID().toString();
        int responseLen=responseContent.getBytes(UTF_8).length;
        /*构建一个协议包*/
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setLen(responseLen);
        messageProtocol.setContent(responseContent.getBytes(UTF_8));

        ctx.writeAndFlush(messageProtocol);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
